package com.mycompany.projektjava2;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author Lukáš Slovák
 * @version 1.1
 */
public class CompanyDAOImpl implements CompanyDAO{
    
    private EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProjektPU");
    // Meno Persistence unit treba dat take ake mas nastavene vo svojom persistence.xml
    
    @Override
    public void create(Company company) {
        if (company != null){
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            em.persist(company);
            em.getTransaction().commit();
            em.close();
        }      
    }

    @Override
    public void remove(Company company) {
        if (company != null){
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            Company company1 = em.find(Company.class, company.getId());
            if (company1 != null){
                em.remove(company1);
            }
            em.getTransaction().commit();
            em.close();
        }  
    }

    @Override
    public void update(Company company) {
        if (company != null){
            Company company1 = find(company.getId());
            if (company1 == null){ return; }
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            company1 = company;
            em.persist(company1);
            em.getTransaction().commit();
            em.close();
        }
    }

    @Override
    public Company find(Long id) {
        EntityManager em = emf.createEntityManager();
        Company result = em.find(Company.class, id);
        em.close();
        return result;
    }

    @Override
    public List<Company> findAll() {
        EntityManager em = emf.createEntityManager();
        
        Query q = em.createQuery("SELECT c FROM Company c"); 
        // musi tu byt skutocny nazov tabulky v databaze
        
        List<Company> result = q.getResultList();
        em.close();
        return result;
    }
    
}
